import java.util.List;

public class TicketService implements Loggable {
    private List<Ticket> ticketList = new java.util.ArrayList<>();

    public Ticket sellTicket(Show show, List<Seat> seats) {
        for (Seat seat : seats) {
            if (!show.getHall().checkSeatAvailable(seat.getRow(), seat.getCol())) {
                return null;
            }
        }

        if (!show.getHall().lockSeats(seats)) {
            return null;
        }

        double totalPrice = calculatePrice(show, seats);
        Ticket ticket = new Ticket(show, seats, totalPrice);
        ticketList.add(ticket);
        show.getTickets().add(ticket);
        
        return ticket;
    }

    private double calculatePrice(Show show, List<Seat> seats) {
        double basePrice = show.getPrice() * seats.size();
        if (show.getTime().getHour() < 14) {
            return basePrice * 0.9;
        }
        return basePrice;
    }

    public boolean refundTicket(String ticketId) {
        for (Ticket ticket : ticketList) {
            if (ticket.getTicketId().equals(ticketId) && ticket.canRefund()) {
                ticket.setRefunded(true);
                ticket.getShow().getHall().unlockSeats(ticket.getSeats());
                ticket.getShow().getTickets().remove(ticket);
                logOperation("退票: " + ticketId);
                return true;
            }
        }
        return false;
    }
}